package com.yuke.cloud.service.wmc.controller.frontend;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yuke.cloud.common.core.support.BaseController;
import com.yuke.cloud.common.util.wrapper.WrapMapper;
import com.yuke.cloud.common.util.wrapper.Wrapper;
import com.yuke.cloud.service.api.uac.dto.GroupInfoDto;
import com.yuke.cloud.service.api.uac.service.UacUserFeignApi;
import com.yuke.cloud.service.wmc.dto.WmsTransPriceDto;
import com.yuke.cloud.service.wmc.entity.WmsTransPrice;
import com.yuke.cloud.service.wmc.entity.WmsWarehouse;
import com.yuke.cloud.service.wmc.service.DicRegionService;
import com.yuke.cloud.service.wmc.service.WmsTransPriceService;
import com.yuke.cloud.service.wmc.service.WmsWarehouseService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zys on 2018/12/07.
 */
@Api(value = "WEB - WmsTransPriceController", tags = "处理WmsTransPrice相关请求", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@RestController
@RequestMapping("/wms/trans_price")
public class WmsTransPriceController extends BaseController {
    @Resource
    private WmsTransPriceService wmsTransPriceService;
    @Resource
    private DicRegionService dicRegionService;
    @Resource
    private WmsWarehouseService wmsWarehouseService;
    @Resource
    private UacUserFeignApi uacUserFeignApi;

    @PostMapping
    @ApiOperation(httpMethod = "POST", value = "新增一条记录")
    public Wrapper add(@ApiParam(name = "wmsTransPrice", value = "该数据记录的POJO") @RequestBody WmsTransPrice wmsTransPrice) {
        if (wmsTransPrice != null) {
            Byte transportType = wmsTransPrice.getTransportType();
            if (transportType.intValue() == 0 || transportType.intValue() == 2) {  // 同城及时达或已快送
                Long regionCityId = wmsWarehouseService.findById(wmsTransPrice.getWarehouseId()).getRegionCityId();
                wmsTransPrice.setRegionIds(regionCityId + "");
            }
            wmsTransPriceService.save(wmsTransPrice);
            return WrapMapper.ok();
        } else {
            return WrapMapper.error();
        }
    }

    @DeleteMapping("/{id}")
    @ApiOperation(httpMethod = "DELETE", value = "根据id删除一条记录")
    public Wrapper delete(@ApiParam(name = "id", value = "记录id") @PathVariable Long id) {
        wmsTransPriceService.deleteById(id);
        return WrapMapper.ok();
    }

    @PutMapping
    @ApiOperation(httpMethod = "PUT", value = "修改一条记录")
    public Wrapper update(@ApiParam(name = "wmsTransPrice", value = "需要修改的内容") @RequestBody WmsTransPrice wmsTransPrice) {
        wmsTransPriceService.update(wmsTransPrice);
        return WrapMapper.ok();
    }

    @GetMapping("/{id}")
    @ApiOperation(httpMethod = "GET", value = "根据ID获取具体信息")
    public Wrapper<WmsTransPrice> detail(@ApiParam(name = "id", value = "记录id") @PathVariable Long id) {
        WmsTransPrice wmsTransPrice = wmsTransPriceService.findById(id);
        String regionIds = wmsTransPrice.getRegionIds();
        WmsWarehouse byId = wmsWarehouseService.findById(wmsTransPrice.getWarehouseId());
        List<String> list1 = new ArrayList<>();
        list1.add(regionIds);
        List<String> list2 = dicRegionService.finprovince(list1);
        wmsTransPrice.setRegionName(list2.get(0));
        wmsTransPrice.setWarehouseName(byId.getWarehouseName());
        return WrapMapper.ok(wmsTransPrice);
    }

    @GetMapping
    @ApiOperation(httpMethod = "GET", value = "分页获取所有记录")
    public Wrapper<PageInfo<WmsTransPrice>> list(@ApiParam(name = "page", value = "分页值", defaultValue = "0") @RequestParam(defaultValue = "0") Integer page,
                                                 @ApiParam(name = "size", value = "每分页返回的记录数", defaultValue = "0") @RequestParam(defaultValue = "10") Integer size,
                                                 @RequestParam(required = false, value = "warehouseId") Long warehouseId) {
        PageHelper.startPage(page, size);
        //获得groupId
        Long groupId = getLoginAuthDto().getGroupId();

        Wrapper<GroupInfoDto> groupInfoDto = uacUserFeignApi.getGroupInfoByGroupId(groupId);
        if (groupInfoDto.getCode()==200){
            // 登录人为3级部门
            if (groupInfoDto.getResult().getLevel().toString().equals("3")){
                groupId = groupInfoDto.getResult().getParentId();
            }
        }
        List<WmsTransPriceDto> wmsTransPriceList = wmsTransPriceService.selectTransPriceInfo(groupId, warehouseId);
        if (wmsTransPriceList == null) {
            return WrapMapper.error("服务异常");
        }

        List<String> regionList = new ArrayList<>();

        for (int i = 0; i < wmsTransPriceList.size(); i++) {
            String regionIds = wmsTransPriceList.get(i).getRegionIds();
            regionList.add(regionIds);

        }

        List<String> provinceNameList = dicRegionService.finprovince(regionList);
        System.out.println(provinceNameList);
        for (int i = 0; i < wmsTransPriceList.size(); i++) {
            wmsTransPriceList.get(i).setRegionName(provinceNameList.get(i));
        }

        PageInfo pageInfo = new PageInfo(wmsTransPriceList);
        return WrapMapper.ok(pageInfo);
    }

    //模板名称唯一性检查
    @GetMapping("/ifUnique")
    public Wrapper ifunique(@RequestParam("templateName") String templateName,
                            @RequestParam(required = false, value = "id") Long id
    ) {
        Example example = new Example(WmsTransPrice.class);
        Example.Criteria criteria = example.createCriteria();
        if (id != null) {
            criteria.andNotEqualTo("id", id);
        }
        criteria.andEqualTo("templateName", templateName);
        List<WmsTransPrice> wmsTransPrices = wmsTransPriceService.selectByExample(example);
        if (wmsTransPrices.size() == 0) {
            return WrapMapper.ok("yes");
        } else {
            return WrapMapper.ok("no");
        }

    }

    //添加运费模板的时候获取所有可以添加的省份
    // mod by wg 20190321 增加订单类型，不同的订单类型运费不一样
    @GetMapping("/getAllProvinceCouldSlect")
    public Wrapper getAllProvinceCouldSlect(@RequestParam(required = false, value = "warehouseId") Long warehouseId,
                                            @RequestParam(required = false, value = "orderType") Byte orderType) {
        if (warehouseId==null||warehouseId.equals("") || orderType==null) {
            List<Map> list5 = new ArrayList<>();
            Map map = new HashMap();
            map.put("regionData", list5);
            return WrapMapper.ok(map);
        }
        //首先获取所有的省份，然后取出已经被绑定的省份
        List<Map> list = dicRegionService.getallprovince();
        List<String> a = new ArrayList<>();
        List<String> b = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            String regionId = list.get(i).get("regionId").toString();
            a.add(regionId);
        }
        Example example = new Example(WmsTransPrice.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("warehouseId", warehouseId);
        criteria.andEqualTo("orderType", orderType);
        List<WmsTransPrice> wmsTransPrices = wmsTransPriceService.selectByExample(example);
        if (wmsTransPrices == null) {
            return WrapMapper.error("服务异常");
        }
        for (int i = 0; i < wmsTransPrices.size(); i++) {
            String regionIds = wmsTransPrices.get(i).getRegionIds();
            String[] split = regionIds.split(",");
            for (int j = 0; j < split.length; j++) {
                b.add(split[j]);
            }
        }
        //a减去所有b的部分
        a.removeAll(b);
        List<Map> list6 = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            if (a.contains(list.get(i).get("regionId").toString())) {
                list6.add(list.get(i));
            }
        }
        Map map = new HashMap();
        map.put("regionData", list6);
        Example example1 = new Example(WmsTransPrice.class);
        Example.Criteria criteria1 = example1.createCriteria();
        criteria1.andEqualTo("warehouseId", warehouseId);
        //criteria1.andEqualTo("transportType", 0);
        List<Byte> transportTypeList = new ArrayList<>();
        transportTypeList.add((byte)0);
        transportTypeList.add((byte)2);
        criteria1.andIn("transportType", transportTypeList);
        criteria1.andEqualTo("orderType", orderType);
        List<WmsTransPrice> wmsTransPrices1 = wmsTransPriceService.selectByExample(example1);
//        if (wmsTransPrices1.size() == 0) {
//            map.put("exists", "no");
//        } else {
//            map.put("id",wmsTransPrices1.get(0).getId());
//            map.put("exists", "yes");
//        }

        if (wmsTransPrices1.size() == 0) {
            map.put("exists_0", "no");
            map.put("exists_2", "no");
        } else {
            int flag = 0;
            for (WmsTransPrice temp : wmsTransPrices1) {
                if (temp.getTransportType() == 0 && (flag & 1) == 0) {  // 即时达
                    map.put("id_0",temp.getId());
                    map.put("exists_0", "yes");
                    flag += 1;
                } else if (temp.getTransportType() == 2 && (flag & 2) == 0) {  // 同城快送
                    map.put("id_2",temp.getId());
                    map.put("exists_2", "yes");
                    flag += 2;
                }
            }

            if ((flag & 1) == 0) {
                map.put("exists_0", "no");
            }

            if ((flag & 2) == 0) {
                map.put("exists_2", "no");
            }
        }

        return WrapMapper.ok(map);
    }

}
